/*
 * @Author: 15956982113 493885262@qq.com
 * @Date: 2025-05-27 17:00:18
 * @LastEditors: 15956982113 493885262@qq.com
 * @LastEditTime: 2025-05-28 14:27:25
 * @FilePath: \v3-webpack\src\router\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHashHistory } from 'vue-router'
import { useCacheStore } from '@/store/cache'

import userList from './user';
const routes = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    meta: {
      keepAlive: true,
      title: '首页'
    }
  },
  {
    path: '/home',
    redirect: '/'
  },
  ...userList
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('路由前置守卫')
  // 显示加载状态
  const loading = document.getElementById('loading')
  if (loading) {
    loading.style.display = 'block'
  }

  // 设置页面标题
  document.title = to.meta.title || '默认标题'

  // 处理缓存
  const cacheStore = useCacheStore()
  if (to.meta.keepAlive) {
    cacheStore.addCache(to.name)
  }
  next()
})

// 全局后置守卫
router.afterEach(() => {
  console.log('全局后置守卫')
  // 隐藏加载状态
  const loading = document.getElementById('loading')
  if (loading) {
    loading.style.display = 'none'
  }
})
// 错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  // 可以跳转到错误页面
  router.push('/error')
})
export default router
